import { flattenObject } from './util'
import jsondiffpatch from 'jsondiffpatch'
import deep from 'deep-get-set'

export function diff (oldTree, tree) {
  const differ = flattenObject(jsondiffpatch.diff(oldTree, tree))
  const keys = Object.keys(differ)

  if (!keys.length) return

  const diffData = []

  new Set(keys.map((key) => {
    if (key.indexOf('._t') > -1) return
    function getDeepKey (str) {
      const reg = new RegExp(str + '\\.\\d+', 'g')
      let match = key.match(reg)
      if (!match) return
      match = match.pop()
      return key.substr(0, key.lastIndexOf(match) + match.length)
    }

    let deepKey = getDeepKey('subViews')
    if (!deepKey) deepKey = getDeepKey('views')
    return deepKey
  })).forEach((key) => {
    if (!key) return
    const target = deep(tree, key)
    const partDiffer = jsondiffpatch.diff(deep(oldTree, key), deep(tree, key))
    Object.keys(partDiffer).forEach((key) => (partDiffer[key] = partDiffer[key][1]))
    diffData.push({ name: target.name, ...partDiffer })
  })

  return diffData
}
